package com.dwin.dingnuo.ui.system;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.TextView;

import com.dwin.dingnuo.R;
import com.dwin.dingnuo.ui.MainActivity;
import com.dwin.dingnuo.ui.base.BaseActivity;
import com.dwin.dingnuo.utils.ActivityUtils;

/**
 * 启动广告页面，内含3s倒计时自动跳转逻辑
 */
public class LoadingActivity extends BaseActivity {

    private static final String TAG = "LoadingActivity";
    private TextView mCountDownTextView;
    private MyCountDownTimer mCountDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);

        mCountDownTextView = findViewById(R.id.start_skip_count_down);
        mCountDownTextView.setText(R.string.s3_jump); //创建倒计时类
        mCountDownTimer = new MyCountDownTimer(3000, 1000);
        mCountDownTimer.start(); //这是一个 Handler 里面的逻辑是从 Splash 界面跳转到 Main 界面，这里的逻辑每个公司基本上一致
        // 倒计时点击，跳转到首页面
        findViewById(R.id.start_skip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCountDownTimer != null) { // 修改倒计时剩余1s左右，点击跳转，会存在2个登录页面的问题。
                    mCountDownTimer.cancel();
                    mCountDownTimer = null;
                }
                jumpToHomePage();
            }
        });
    }

    // 用户首次使用，进入引导页面；非首次使用，进入主页面
    private void jumpToHomePage() {
        // 已登录用户，进入首页面；未登录用户，进入登录页面
        if (mUser != null) {
            ActivityUtils.switchActivityFinish(LoadingActivity.this, MainActivity.class);
        } else {
            ActivityUtils.switchActivityFinish(LoadingActivity.this, LoginActivity.class);
        }
    }

    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        public void onFinish() {
            jumpToHomePage();
        }

        public void onTick(long millisUntilFinished) {
            mCountDownTextView.setText(millisUntilFinished / 1000 + getResources().getString(R.string.s_jump));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
    }

}
